package net.golfklubi.sive;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.thoughtworks.xstream.converters.SingleValueConverter;

public class MySinglevalueConverter implements SingleValueConverter {
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");

    @Override
    public Object fromString(final String str) {
        if ("".equals(str.trim())) {
            return null;
        }
        try {
            return new LocalDate(simpleDateFormat.parse(str));
        } catch (final ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString(final Object obj) {
        final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(new Locale("fi"));
        return ((LocalDate) obj).toString(dateTimeFormatter);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean canConvert(final Class type) {
        if (type.equals(LocalDate.class)) {
            return true;
        }
        return false;
    }

}
